<?php
namespace app\index\controller;

use app\index\model\FacebookPage;
use app\index\model\MessageUser;
use CURLFile;
use think\Controller;
use think\Exception;
use think\Request;

class FaceBook extends Controller
{
    protected static $host='https://graph.facebook.com';

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public function webHook(){
        $post=input('post.');
        $get=input('get.');

        trace('post data' . json_encode($post), 'debug');
//        trace('get data' . json_encode($get), 'debug');
        try {
            $accessToken = "EAAH5VzVXzoYBAGRJXo40tm9EZBtOMFNKPSnIruYRGciNiofdrS8I0yuH5AyQbDIjfZCoWEYCHKd5NpH6LHgaSQmPiaqzLG0XLiFKaLNu3O8CPHtZBXsHs9XAtdRwufmQHXeA7yXByzPK5KlsdvuVyXTMhuZBeh61grWQYinus7MFHkMYavdh1UhblDlR8jYZAYPEwAx76PgZDZD";

            if (!empty($get)) {
                if (isset($get['hub_mode'], $get['hub_verify_token'], $get['hub_challenge']) && $get['hub_mode'] === 'subscribe' && $get['hub_verify_token'] === $accessToken) {
//                    trace('verify success', $get['hub_challenge'],'debug');
                    exit($get['hub_challenge']);
                }
//                trace('verify error ' . json_encode($get), 'debug');
            }
            $senderId = $post['entry'][0]['messaging'][0]['sender']['id'];
            $messageText = $post['entry'][0]['messaging'][0]['message']['text']??'';
            $pageId=$post['entry'][0]['id'];
            $timestamp=ceil($post['entry'][0]['time']/1000);


            $MessageUserClass=new MessageUser();
            $page_data=FacebookPage::where('page_id','=',$pageId)->field('id,access_token')->find();
            if(empty($page_data)){
                throw new Exception('Unsupported homepage');
            }
            $message_user=['ps_id'=>$senderId,'page_id'=>$page_data['id']];
            $message_user_data=$MessageUserClass->where('ps_id','=',$senderId)->where('page_id',$page_data['id'])->field('id,full_name')->select()->toArray();
            if(empty($message_user_data)){
                $message_user_data=[];
            }else{
                $message_user_data=$message_user_data[0];
            }

            $MessageUserClass->startTrans();
            try {
                if(isset($message_user_data['id'])) {
                    $result = $MessageUserClass->where('id', '<>', $message_user_data['id'])->where('ps_id', '=', $senderId)->where('page_id', '=', $page_data['id'])->update(['del_flag' => 1]);
                    if ($result === false) {
                        throw new Exception('delete repeat user error');
                    }
                }
                if (!isset($message_user_data['id'])) {
                    $message_user['first_time'] = date('Y-m-d H:i:s', $timestamp);
                    $message_user['last_time'] = date('Y-m-d H:i:s', $timestamp);
                    $result=$MessageUserClass->isUpdate(false)->save($message_user);
                    if($result===false){
                        throw new Exception('message user save error');
                    }
                } /*else {
                    $message_user['id'] = $message_user_data['id'];
                    $message_user['last_time'] = date('Y-m-d H:i:s', $timestamp);
                    $result=$MessageUserClass->isUpdate(true)->save($message_user);
                }*/
                $MessageUserClass->commit();
            }catch (Exception $e){
                $MessageUserClass->rollback();
                trace('facebook webhook 
                '.$e->getLine().'' .$e->getMessage().'
                '. json_encode($message_user), 'error');
            }
            $response=[];

/*            if($page_data['id']!==3 && $page_data['id']!==7) {
                trace($page_data['id'],'debug');
                return json(['code' => 0, 'msg' => ''], 200);
            }*/

            $text=strtolower($messageText);
            if ($text === "can you introduce your company for me?") {
                $answer = 'Hi dear , our factory is based in guangdong province, zhuhai city. our headquarter is located in Hongkong. Cobor is very famous in china.';
                $response = [
                    'recipient' => ['id' => $senderId],
                    'message' => ['text' => $answer]
                ];
            }elseif($text==='info'){
                $answer = 'Hi dear , for more information, you can go to our website https://buy.cobor.shop to check';
                $response = [
                    'recipient' => ['id' => $senderId],
                    'message' => ['text' => $answer]
                ];
            }elseif($text==='menu'){
                $answer = 'hi dear , our star products include eye mask and face cream. just type the name so you can learn more';
                $response = [
                    'recipient' => ['id' => $senderId],
                    'message' => ['text' => $answer]
                ];
            }elseif($text==='how to order'){
                $answer = 'hi dear ,you can order from me , or on our facebook ins live, or web cobor.shop,once you comfirm, pls send your email and home address, we do COD service';
                $response = [
                    'recipient' => ['id' => $senderId],
                    'message' => ['text' => $answer]
                ];
            }elseif($text==='eye mask'){
                $answer = 'hi,dear  .our eye masks 56 SGD for 3 packs,total 15 pair, and 1 seaweed cleanser for free!';
                $response = [
                    'recipient' => ['id' => $senderId],
                    'message' => ['text' => $answer]
                ];
            }elseif($text==='face cream'){
                $answer = 'what can I do for you? type info to get more information, type menu to get more menu.';
                $response = [
                    'recipient' => ['id' => $senderId],
                    'message' => ['text' => $answer]
                ];
            }else{
                $answer = 'what can I do for you? type info to get more information, type menu to get more menu.';
                $response = [
                    'recipient' => ['id' => $senderId],
                    'message' => ['text' => $answer]
                ];
            }
            if (!empty($response)) {
                $ch = curl_init('https://graph.facebook.com/v11.0/me/messages?access_token=' . $page_data['access_token']);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                $result = curl_exec($ch);
                $error = curl_error($ch);
                curl_close($ch);
                if ($error) {
                    trace('send error ' . json_encode($error), 'error');
                }
                if (isset($result['error'])) {
                    trace('send error ' . json_encode($result) . ' id' . $senderId, 'error');
                }
            }

        }catch (Exception $exception){
            trace('facebook webhook error
            ' .$exception->getLine().'
            ' . $exception->getMessage(), 'error');
        }
        return json(['code'=>0,'msg'=>''],200);
    }

    public static function sendMessage($accessToken,$message_data,$senderId): array
    {
        try {
            $length = count($senderId);

            $request_times = ceil($length / 150);
            $request_count = 0;
            $request_send = 0;
            for ($i = 0; $i < $request_times; $i++) {
                $mh = curl_multi_init();
                $request_end = ($i + 1) * 150;
                for ($request_count; $request_count <= $request_end; $request_count++) {
                    if ($request_count > ($length - 1)) {
                        break;
                    }
                    $response = [
                        'recipient' => ['id' => $senderId[$request_count]],
                        'message' =>$message_data
                    ];
                    $ch[$request_count] = curl_init();
                    curl_setopt_array($ch[$request_count], array(
                        CURLOPT_URL => self::$host . '/v11.0/me/messages?access_token=' . $accessToken,
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_ENCODING => '',
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_TIMEOUT => 10,
                        CURLOPT_FOLLOWLOCATION => true,
                        CURLOPT_SSL_VERIFYPEER => true,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_POSTFIELDS => json_encode($response),
                        CURLOPT_CUSTOMREQUEST => 'POST',
                        CURLOPT_HTTPHEADER => array(
                            'Content-Type: application/json'
                        ),
                    ));
                    curl_multi_add_handle($mh, $ch[$request_count]);
                }
                $active = null;
                do {
                    $mrc = curl_multi_exec($mh, $active);
                } while ($mrc === CURLM_CALL_MULTI_PERFORM);

                while ($active && $mrc == CURLM_OK) {
                    if (curl_multi_select($mh) != -1) { //阻塞直到cURL批处理连接中有活动连接。
                        do {
                            $mrc = curl_multi_exec($mh, $active);
                        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
                    }
                }
                for ($request_send; $request_send <= $request_end; $request_send++) {
//                $info = curl_multi_info_read($mh);
//                $header = curl_getinfo($value);
                    if ($request_send > ($length - 1)) {
                        break;
                    }
                    $result = curl_multi_getcontent($ch[$request_send]);

                    $error = curl_error($ch[$request_send]);
                if($error) {
                    trace('send error ' . $error . ' id' . $senderId[$request_send], 'error');
                    return ['status'=>false,'msg'=>'发送失败 '.$error];
                }

                    $result = json_decode($result, true);
                if(isset($result['error'])) {
                    trace('send error ' . json_encode($result) . ' id' . $senderId[$request_send], 'error');
                    return ['status'=>false,'msg'=>'发送失败 '.$result['error']['message']??''];
                }
                    curl_multi_remove_handle($mh, $ch[$request_send]);
                    curl_close($ch[$request_send]);
                }
                $error = curl_multi_errno($mh);
//                trace('curl multi error' . json_encode($error), 'debug');
                curl_multi_close($mh);
                sleep(1);
            }
            return ['status'=>true,'msg'=>'发送成功'];
        }catch (Exception $e){
            trace('send message error'.$e->getMessage(),'error');
            return ['status'=>false,'msg'=>'发送失败'];
        }
    }

    public static function attachmentsUpload($accessToken,$file){
        $curl = curl_init();

        $image = @getimagesize($file);
        $name = basename($file);
        curl_setopt_array($curl, array(
            CURLOPT_URL => self::$host .'/v11.0/me/message_attachments?access_token='.$accessToken,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array('message' => '{"attachment":{"type":"image", "payload":{"is_reusable":true}}}','filedata'=> new CURLFILE($file,$image['mime'],$name)),
        ));

        $result = curl_exec($curl);
        $result=json_decode($result,true);
        $error = curl_error($curl);
        curl_close($curl);
        if ($error) {
            trace('attachments curl error ' . json_encode($error), 'error');
            return ['status'=>false,'msg'=>'保存附件失败'];
        }
        if(isset($result['error'])) {
            trace('attachments error ' . json_encode($result), 'error');
            return ['status'=>false,'msg'=>'保存附件失败'];
        }
        return ['status'=>true,'msg'=>$result['attachment_id']];
    }

    public static function userProfile($accessToken,$ps_id){
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => self::$host .'/'.$ps_id.'?fields=name&access_token='.$accessToken,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
        ));
        $result = curl_exec($curl);
        $error = curl_error($curl);
        curl_close($curl);
        if ($error) {
            trace('user profile curl error ' . json_encode($error), 'error');
            return ['status'=>false,'msg'=>'查询失败'];
        }
        if(isset($result['error'])) {
            trace('user profile error ' . json_encode($result), 'error');
            return ['status'=>false,'msg'=>'查询失败'];
        }
        return ['status'=>true,'msg'=>json_decode($result,true)];
    }

    public static function instagramPageId($accessToken,$page_id){
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => self::$host.'/v5.0/'.$page_id.'?fields=instagram_business_account&access_token='.$accessToken,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
        ));

        $result = curl_exec($curl);
        $error = curl_error($curl);
        $result=json_decode($result,true);
        curl_close($curl);
        if ($error) {
            trace('instagram page curl error ' . json_encode($error), 'error');
            return ['status'=>false,'msg'=>'查询失败'];
        }
        if(isset($result['error'])) {
            trace('instagram page error ' . json_encode($result), 'error');
            return ['status'=>false,'msg'=>'查询失败'];
        }
        if(!isset($result['instagram_business_account']['id'])){
            trace('instagram page error ' . json_encode($result), 'error');
            return ['status'=>false,'msg'=>'查询失败'];
        }
        $instagram_business_account=$result['instagram_business_account'];
        return ['status'=>true,'msg'=>$instagram_business_account];
    }

}